<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <title>{$device.name}</title>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://res2.wx.qq.com/open/js/jweixin-1.4.0.js"></script>

    <link rel="stylesheet" href="__STATIC__/frozenui-2.0.0/release/css/frozenui.css"/>
    <link rel="stylesheet" href="__STATIC__/frozenui-2.0.0/release/demo/css/style.css">


    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vant@2.0/lib/index.css">
    <link href="https://unpkg.com/angular-radial-color-picker@latest/dist/css/color-picker.min.css" rel="stylesheet">


    <!-- 引入组件 -->
    <script src="https://cdn.jsdelivr.net/npm/vant@2.0/lib/vant.min.js"></script>

    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/@radial-color-picker/vue-color-picker/dist/vue-color-picker.cjs.js"></script>
    <script src="https://unpkg.com/@radial-color-picker/vue-color-picker/dist/vue-color-picker.esm.js"></script>
    <script src="https://unpkg.com/@radial-color-picker/vue-color-picker/dist/vue-color-picker.umd.js"></script>
    <link href="https://unpkg.com/@radial-color-picker/vue-color-picker/dist/vue-color-picker.min.css" rel="stylesheet">


    <!-- 引入组件 -->
    <script type="text/javascript" src="__STATIC__/colorpicker/farbtastic.js"></script>
    <link rel="stylesheet" href="__STATIC__/colorpicker/farbtastic.css" type="text/css"/>


    <link rel="stylesheet" href="__STATIC__/weui+/css/weui.css"/>
    <link rel="stylesheet" href="__STATIC__/weui+/css/weuix.css"/>

    <script src="__STATIC__/weui+/js/zepto.min.js"></script>
    <script src="__STATIC__/weui+/js/zepto.weui.js"></script>


    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/vue-slider-component@latest/theme/default.css">
    <script src="__STATIC__/slider/vue-slider-component.umd.min.js"></script>
    <script type="text/javascript" src="__STATIC__/mqtt/mqtt.js"></script>


    <!-- 全局css样式 -->
    <style>

        .ui-flex {
            margin-top: 40px;
            border: white;
        }

        .ui-btn-lg {
            margin-top: 40px;
            border: white;
        }
    </style>

</head>
<body ontouchstart>
<section class="ui-container">
    <section id="layout">
        <div id="app" class="demo-item">
            <div id="load" class="ui-loading-block ui-flex show">
                <div class="ui-loading-cnt">
                    <i class="ui-loading-bright"></i>
                    <p>正在加载中...</p>
                </div>
            </div>
            <div class="ui-flex ui-flex-pack-center">
                <!--v-on:change="headleChangeColor"-->
                <color-picker v-bind="color" @input="onAlter" v-on:change="headleChangeColor"></color-picker>
            </div>


            <div class="ui-btn-group ui-border-t">
                <button @click="clickRed" class="ui-btn-lg" style="color: rgb(255,0,0)">
                    红色
                </button>
                <button @click="clickGreen" class="ui-btn-lg" style="color: rgb(0,255,0)">
                    绿色
                </button>
                <button @click="clickBlue" class="ui-btn-lg" style="color: rgb(0,0,255)">
                    蓝色
                </button>
            </div>


            <div style="padding: 10px ; padding-top: 50px">
                <p class="ui-flex-pack-left" style="font-size: 15px ; color: black">亮度调节:</p>
                <vue-slider v-model="valueSlideRed" v-bind="sliderStyle"
                            :lazy="true"
                            :height="10"
                            :process-style="{ backgroundColor: 'black' }"
                            :tooltip-style="{ backgroundColor: 'black', borderColor: 'black' }"
                            @change="LightSliderCallback">
                </vue-slider>
            </div>

            <div style="padding: 10px">
                <div class="ui-flex-pack-left" style="font-size: 15px  ; color: black">色温调节:</div>
                <vue-slider v-model="valueSlideGreen" v-bind="sliderStyle"
                            :lazy="true"
                            :height="10"
                            :process-style="{ backgroundColor: 'black' }"
                            :tooltip-style="{ backgroundColor: 'black', borderColor: 'black' }"
                            @change="TemperSliderCallback">
                </vue-slider>
            </div>


            <div class="weui-footer weui-footer_fixed-bottom">
                <p class="weui-footer__text">Copyright &copy; 半颗心脏</p>
            </div>

        </div>
        </div>
    </section>
</section>

<script>


    //对浏览器的UserAgent进行正则匹配，不含有微信独有标识的则为其他浏览器
    var useragent = navigator.userAgent;
    if (useragent.match(/WindowsWechat/) == 'WindowsWechat' || useragent.match(/MicroMessenger/i) != 'MicroMessenger') {
        // 这里警告框会阻塞当前页面继续加载
        //alert('已禁止本次访问：您必须使用微信内置浏览器访问本页面！');
        document.head.innerHTML = '<title>抱歉，出错了</title><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0"><link rel="stylesheet" type="text/css" href="https://res.wx.qq.com/open/libs/weui/0.4.1/weui.css">';
        document.body.innerHTML = '<div class="weui_msg"><div class="weui_icon_area"><i class="weui_icon_info weui_icon_msg"></i></div><div class="weui_text_area"><h4 class="weui_msg_title">请在微信客户端打开链接</h4></div></div>';
    }
    $("#load").show();

    function rgbToHsl(r, g, b) {

        r /= 255, g /= 255, b /= 255;

        var max = Math.max(r, g, b), min = Math.min(r, g, b);

        var h, s, l = (max + min) / 2;

        if (max == min) {

            h = s = 0; // achromatic

        } else {

            var d = max - min;

            s = l > 0.5 ? d / (2 - max - min) : d / (max + min);

            switch (max) {

                case r:
                    h = (g - b) / d + (g < b ? 6 : 0);
                    break;

                case g:
                    h = (b - r) / d + 2;
                    break;

                case b:
                    h = (r - g) / d + 4;
                    break;

            }

            h /= 6;

        }

        return [Math.floor(h * 100), Math.round(s * 100), Math.round(l * 100)];

    }

    let connectInfo = {$config};
    console.log(('connectInfo:'), JSON.stringify(connectInfo));
    let options = {
        protocolVersion: 4, //MQTT连接协议版本
        clean: false,
        reconnectPeriod: 1000, //1000毫秒，两次重新连接之间的间隔
        connectTimeout: 30 * 1000, //1000毫秒，两次重新连接之间的间隔
        resubscribe: true, //如果连接断开并重新连接，则会再次自动订阅已订阅的主题（默认true）
        clientId: connectInfo.clientId,
        password: connectInfo.mqtt.password,
        username: connectInfo.mqtt.username,
    };

    let mqttClient = mqtt.connect(connectInfo.mqtt.url, options);

    var ColorPicker = window.VueColorPicker;
    let app = new Vue({
        el: '#app',
        components: {
            ColorPicker: ColorPicker,
            VueSlider: window['vue-slider-component'],
        },
        data: {
            clientMqtt: mqttClient,
            topicSub: connectInfo.topicSub,
            valueSlideRed: 0,
            valueSlideGreen: 0,
            valueSlideBlue: 0,
            colorAlterCounts: 0,
            color: {
                hue: 50,
                saturation: 100,
                luminosity: 50,
                alpha: 1
            },
            sliderStyle: {
                width: '100%',
                show: false,
                value: [0, 100],
                min: 0,
                max: 100,
                piecewiseLabel: true,
                tooltip: 'none',
                tooltipDir: [
                    "bottom",
                    "top"
                ]
            },
            controlData: {
                header: {
                    name: "SetColor",
                    namespace: "AliGenie.Iot.DeviceCenter.Mine",
                    payLoadVersion: 1
                },
                payload: {
                    attribute: "color",
                    deviceId: connectInfo.deviceId,
                    deviceType: "light",
                    value: "Blue"
                }
            }
        },
        methods: {
            hslToRgb: function (h, s, l) {
                var r, g, b;


                if (s == 0) {

                    r = g = b = l; // achromatic

                } else {

                    var hue2rgb = function hue2rgb(p, q, t) {

                        if (t < 0) t += 1;

                        if (t > 1) t -= 1;

                        if (t < 1 / 6) return p + (q - p) * 6 * t;

                        if (t < 1 / 2) return q;

                        if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;

                        return p;

                    }


                    var q = l < 0.5 ? l * (1 + s) : l + s - l * s;

                    var p = 2 * l - q;

                    r = hue2rgb(p, q, h + 1 / 3);

                    g = hue2rgb(p, q, h);

                    b = hue2rgb(p, q, h - 1 / 3);
                }
                return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
            },
            headleChangeColor: function (hue) {
                this.color.hue = hue;
                var obj = this.hslToRgb(hue / 360, 1, 0.5);
                this.controlData.header.name = 'SetColor';
                this.controlData.payload.attribute = "color";
                this.controlData.payload.value = obj;
                this.clientMqtt.publish(this.topicSub, JSON.stringify(this.controlData));
            },
            onAlter: function (color) {
            },
            clickRed: function () {
                this.controlData.payload.value = [255, 0, 0]
                this.controlData.header.name = 'SetColor';
                this.controlData.payload.attribute = "color";
                this.clientMqtt.publish(this.topicSub, JSON.stringify(this.controlData))
            }
            ,
            clickBlue: function () {
                this.controlData.payload.value = [0, 0, 255]
                this.controlData.header.name = 'SetColor';
                this.controlData.payload.attribute = "color";
                this.clientMqtt.publish(this.topicSub, JSON.stringify(this.controlData))
            }
            ,
            clickGreen: function () {
                this.controlData.header.name = 'SetColor';
                this.controlData.payload.attribute = "color";
                this.controlData.payload.value = [0, 255, 0]
                this.clientMqtt.publish(this.topicSub, JSON.stringify(this.controlData))
            }
            ,
            LightSliderCallback: function (value) {
                this.valueSlideRed = value;
                this.controlData.payload.value = value
                this.controlData.header.name = 'SetBrightness';
                this.controlData.payload.attribute = "brightness";
                console.log(('RedSliderCallback') + value);
            },
            TemperSliderCallback: function (value) {
                this.valueSlideGreen = value;
                this.controlData.payload.value = value
                this.controlData.header.name = 'SetColorTemperature';
                this.controlData.payload.attribute = "colorTemperature";
                console.log(('RedSliderCallback') +  this.controlData.payload.value);
            }
        }
    })

    //服务器连接异常的回调
    mqttClient.on("error", function (error) {
        console.log(" 服务器 error 的回调" + error)
    });

    //服务器重连连接异常的回调
    mqttClient.on("reconnect", function () {
        console.log(" 服务器 reconnect的回调")
    });
    //服务器连接异常的回调
    mqttClient.on("offline", function (errr) {
        console.log(" 服务器offline的回调")
    });

    function buf2string(buffer) {
        var arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
        var str = '';
        for (var i = 0; i < arr.length; i++) {
            str += String.fromCharCode(arr[i])
        }
        return str
    }

    //服务器连接异常的回调
    mqttClient.on("message", function (client, topic, payload) {
        $("#load").hide();
        //console.log(" 收到消息回调payload:", buf2string(topic));
        let attr = JSON.parse(buf2string(topic)).attr;
        console.log(" 收到消息回调", attr);
        var rgbValue = rgbToHsl(attr[1].rgb[0], attr[1].rgb[1], attr[1].rgb[2]);
        app._data.color.hue = rgbValue[0] / 100 * 360
    });

    //服务器连接ok的回调
    mqttClient.on("connect", function (errr) {
        $("#load").hide();
        //console.log(" 服务器connect的回调", connectInfo.topicPub)
        mqttClient.subscribe(connectInfo.topicPub)
        app._data.controlData.header.name = 'Query';
        mqttClient.publish(connectInfo.topicSub, JSON.stringify(app._data.controlData))
        app._data.controlData.header.name = 'SetColor'
    });


</script>

</body>


</html>


